package com.roc.web.action;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionSupport;
import com.roc.service.IUserService;
import com.roc.util.NewFtpUtils;
import com.roc.util.Utils;

import net.sf.json.JSONObject;


/**
 * 图片处理的action
 *
 */
/**
 * @author Administrator
 *
 */
@Component
@Namespace("/upload")
@Scope("prototype")
public class ProcessImageAction extends ActionSupport {
	
	private static Logger logger=LogManager.getLogger(ProcessImageAction.class);
	private static final long serialVersionUID = 1L;
	
	@Autowired
	private IUserService  userService;
	 	private File[] file;              //文件  
	    private String[] fileFileName;    //文件名   
	    private String type;
	    private String deleteUrl;
	    private String isMid;
	    private String orgCodes;
	    private String changeType;  //变更类型
	    private String timestamp;   //时间字符串   YYYYMMDDHHMM
	    private String accountNo; //云商宝会员账号
	/**
	 * 图片上传
	 * 
	 * @return
	 */
	@Action(value = "uploadImage")
	public String upload() {
		HttpServletResponse response = ServletActionContext.getResponse();
		
	    response.setCharacterEncoding("UTF-8");
		JSONObject jsonObject = new JSONObject();
		PrintWriter out = null;
		logger.info("上传本地参数-->file="+file+"--->type="+type+"--->isMid="+isMid+"--->orgCodes="+orgCodes);
		try {
			if (this.file != null) {
				for (int i = 0; i < file.length; i++) {
					String fileName = isMid+type+"0"+i+1; // 采用时间+UUID的方式随即命名
					String fileType = fileFileName[i].substring(fileFileName[i].lastIndexOf(".")).toLowerCase(); // 保存文件类型
					String name=fileName+ fileType;
					String filePath=orgCodes+File.separator+isMid;
					File srcFile = file[i];
					boolean result=NewFtpUtils.handleFiles(srcFile, filePath,name);
					if(result){
						jsonObject.put("date",name);
						jsonObject.put("statusCode", "success");
						jsonObject.put("message", "上传成功");
					}else{
						jsonObject.put("date","");
						jsonObject.put("statusCode", "fail");
						jsonObject.put("message", "上传失败");
					}
					//boolean flag = FtpUtil.upload(srcFile, filePath, name);
					/*String image_usr= Utils.getConfigValue("img_domain")+File.separator+filePath+File.separator+name;
					logger.info("上传本地去掉盘符的路径结束path="+image_usr);*/
					
					//jsonObject.put("date",image_usr);
					
				}
			} else {
				jsonObject.put("statusCode", "fail");
				jsonObject.put("message", "上传文件不存在");

			}
			out = response.getWriter();
		} catch (Exception e) {
			jsonObject.put("statusCode", "fail");
			jsonObject.put("message", "上传文件异常");
			logger.info("错误日志 Exception="+e.getMessage());
		}
		out.print(jsonObject.toString());
		out.flush();
		out.close();
		return null;
	}
	
	/**
	 * 变更图片上传
	 * 
	 * @return
	 */
	@Action(value = "uploadChangeImage")
	public String uploadchange() {
		HttpServletResponse response = ServletActionContext.getResponse();
		
	    response.setCharacterEncoding("UTF-8");
		JSONObject jsonObject = new JSONObject();
		PrintWriter out = null;
		logger.info("上传本地参数-->file="+file+"--->type="+type+"--->isMid="+isMid+"--->orgCodes="+orgCodes+"-->changeType"+changeType+"-->timestamp"+timestamp);
		try {
			if (this.file != null) {
				for (int i = 0; i < file.length; i++) {
					String fileName = isMid+type+"0"+i+1; // 采用时间+UUID的方式随即命名
					String fileType = fileFileName[i].substring(fileFileName[i].lastIndexOf(".")).toLowerCase(); // 保存文件类型
					String name=fileName+ fileType;
					String filePath=orgCodes+File.separator+isMid+File.separator+changeType+File.separator+timestamp;//时间格式改为
					File srcFile = file[i];
					boolean result=NewFtpUtils.handleFiles(srcFile, filePath,name);
					if(result){
						jsonObject.put("date",name);
						jsonObject.put("statusCode", "success");
						jsonObject.put("message", "上传成功");
					}else{
						jsonObject.put("date","");
						jsonObject.put("statusCode", "fail");
						jsonObject.put("message", "上传失败");
					}
					//boolean flag = FtpUtil.upload(srcFile, filePath, name);
					/*String image_usr= Utils.getConfigValue("img_domain")+File.separator+filePath+File.separator+name;
					logger.info("上传本地去掉盘符的路径结束path="+image_usr);*/
					
					//jsonObject.put("date",image_usr);
					
				}
			} else {
				jsonObject.put("statusCode", "fail");
				jsonObject.put("message", "上传文件不存在");

			}
			out = response.getWriter();
		} catch (Exception e) {
			jsonObject.put("statusCode", "fail");
			jsonObject.put("message", "上传文件异常");
			logger.info("错误日志 Exception="+e.getMessage());
		}
		out.print(jsonObject.toString());
		out.flush();
		out.close();
		return null;
	}
	
	/**
	 * 上传云商宝会员解限图片(担保函照片)
	 * @return
	 */
	@Action(value = "uploadYsbImg")
	public String uploadYsbImg(){
		HttpServletResponse response = ServletActionContext.getResponse();
			response.setCharacterEncoding("UTF-8");
			JSONObject jsonObject = new JSONObject();
			PrintWriter out = null;
			logger.info("上传本地参数-->file="+file+"-->accountNo="+accountNo+"-->timestamp="+timestamp);
			try {
				if(this.file != null){
					for(int i = 0; i < file.length; i++){
						String fileName = "L_"+timestamp;
						String fileType = fileFileName[i].substring(fileFileName[i].lastIndexOf(".")).toLowerCase();
						String name = fileName + fileType;
						String filePath = accountNo;
						File srcFile = file[i];
						boolean result = NewFtpUtils.handleYsbFiles(srcFile, filePath, name);
						if(result){
							jsonObject.put("date",name);
							jsonObject.put("statusCode", "success");
							jsonObject.put("message", "上传成功");
						}else{
							jsonObject.put("date","");
							jsonObject.put("statusCode", "fail");
							jsonObject.put("message", "上传失败");
						}
					}
				}else {
					jsonObject.put("statusCode", "fail");
					jsonObject.put("message", "上传文件不存在");
				}
				out = response.getWriter();
			} catch (Exception e) {
				jsonObject.put("statusCode", "fail");
				jsonObject.put("message", "上传文件异常");
				logger.info("错误日志 Exception="+e.getMessage());
			}
			out.print(jsonObject.toString());
			out.flush();
			out.close();
			return null;
	}
	
	
	
	/**
	 * 图片上传
	 * 
	 * @return
	 */
	@Action(value = "informationImg")
	public String informationUpload() {
		HttpServletResponse response = ServletActionContext.getResponse();
	    response.setCharacterEncoding("UTF-8");
		JSONObject jsonObject = new JSONObject();
		PrintWriter out = null;
		logger.info("上传本地参数-->file="+file+"--->type="+type);
		try {
			if (this.file != null) {
				for (int i = 0; i < file.length; i++) {
					String fileName = java.util.UUID.randomUUID().toString(); // 采用时间+UUID的方式随即命名
					String fileType = fileFileName[i].substring(fileFileName[i].lastIndexOf(".")); // 保存文件类型
					String key = fileName+ fileType;//去掉盘符的路径
					String filePath=Utils.getConfigValue("information_folder");
					File srcFile = file[i];
					//boolean flag = FtpUtil.upload(srcFile, filePath, key);
					 String showUrl= Utils.getConfigValue("img_domain")+File.separator+filePath+File.separator+key;
					 logger.info("showUrl="+showUrl+"___key="+key);
					jsonObject.put("url", showUrl);
					jsonObject.put("date",key);
					jsonObject.put("statusCode", "success");
					jsonObject.put("message", "上传成功");
				}
			} else {
				jsonObject.put("statusCode", "fail");
				jsonObject.put("message", "上传文件不存在");

			}
			out = response.getWriter();
		} catch (Exception e) {
			jsonObject.put("statusCode", "fail");
			jsonObject.put("message", "上传文件异常");
			logger.info("错误日志 Exception="+e.getMessage());
		}
		out.print(jsonObject.toString());
		out.flush();
		out.close();
		return null;
	}
	
	
	
	/**
	 * http请求图片流
	 * @param response
	 * @param url 图片服务器地址 +图片路径
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	@Action(value = "showImg", interceptorRefs = @InterceptorRef("defaultStack"))
	public  void readImageGet() throws   Exception {
		HttpServletResponse response= ServletActionContext.getResponse();
		HttpServletRequest  request=ServletActionContext.getRequest();
		 
		InputStream in=null;
		OutputStream os=null;
		ByteArrayOutputStream baos=null;
		CloseableHttpClient httpclient=null;
		String path;
		 try {
			 String id =request.getParameter("mid");//
			 String org = request.getParameter("orgs");//
			 String type =request.getParameter("changeType");
			 String time =request.getParameter("timestamp");
			 if(null==id || org==null){
				 logger.info("----图片名称或者机构获取失败-----");
				 return;
			 }
			
			logger.info("-----图片名称["+id+"]/机构["+org+"]------");
			
			if("850".equals(id.substring(0, 3))){
				if(null==type ||  null==time){
					logger.info("----变更类型或变更时间获取失败-----");
					 return;
				}else{
					path=Utils.getConfigValue("img_domain")+"/"+org+"/"+id.substring(0, 15)+"/"+type+"/"+time+"/"+id;
				}
			}else{
				path=Utils.getConfigValue("img_domain")+"/"+org+"/"+id.substring(0, 15)+"/"+id;
			}
			
			System.out.println(path);
			httpclient = HttpClients.createDefault();
			HttpGet httpGet = new HttpGet(path);
			HttpResponse response2 = httpclient.execute(httpGet);
			in = response2.getEntity().getContent();
			baos= new ByteArrayOutputStream();
			int temp = 0;
			byte[] buffer = new byte[1024];
			while ((temp = in.read(buffer)) != -1) {
				baos.write(buffer, 0, temp);
			}
			//in.read(baos.toByteArray()); // 读数据
			
			os= response.getOutputStream();
			os.write(baos.toByteArray());
			
			  
		} catch (Exception e) {
			logger.error("显示图片路径失败="+e);
			throw new Exception("显示图片路径失败=",e);
		}finally {
			if(in!=null){
				in.close();  
			}
			if(baos!=null){
				baos.flush();
				baos.close();
			}
			if(os!=null){
				os.flush();
				os.close();
			}
			if(httpclient!=null){
				httpclient.close();
			}
		}

		 
	}
	/**
	 * 图片删除
	 * 
	 * @return
	 *//*
	@Action(value = "deleteImage")
	public String deleteImage() {
		
		//image\62908e2e-a052-440d-a8bf-0941af289cf1.png
		HttpServletResponse response = ServletActionContext.getResponse();
		JSONObject jsonObject = new JSONObject();
		PrintWriter out = null;
		try {
			if (this.deleteUrl != null) {
					path += deleteUrl;//本地路径
					//上传到本地
					 FtpUtil.deleteFileFtp(srcFile, information_folder, key);
					jsonObject.put("statusCode", "success");
				
			} else {
				jsonObject.put("statusCode", "fail");
				jsonObject.put("message", "删除文件不存在");

			}
			out = response.getWriter();
		} catch (Exception e) {
			logger.info("错误日志 Exception="+e.getMessage());
		}
		out.print(jsonObject.toString());
		out.flush();
		out.close();
		return null;
	}
	*/

	
	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getIsMid() {
		return isMid;
	}

	public void setIsMid(String isMid) {
		this.isMid = isMid;
	}

	public File[] getFile() {
		return file;
	}

	public void setFile(File[] file) {
		this.file = file;
	}

	public String[] getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String[] fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getDeleteUrl() {
		return deleteUrl;
	}

	public void setDeleteUrl(String deleteUrl) {
		this.deleteUrl = deleteUrl;
	}

	public String getOrgCodes() {
		return orgCodes;
	}

	public void setOrgCodes(String orgCodes) {
		this.orgCodes = orgCodes;
	}

	public String getChangeType() {
		return changeType;
	}

	public void setChangeType(String changeType) {
		this.changeType = changeType;
	}

	public String getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(String timestamp) {
		this.timestamp = timestamp;
	}

	public String getAccountNo() {
		return accountNo;
	}

	public void setAccountNo(String accountNo) {
		this.accountNo = accountNo;
	}
	
}